<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图片类型" prop="picType">
        <el-select v-model="queryParams.picType" placeholder="请选择图片类型" clearable>
          <el-option
            v-for="dict in manage_pic_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="数据推送状态" prop="conTime">
        <el-input
          v-model="queryParams.condition"
          placeholder="请输入数据推送状态"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="推送次数" prop="pushCount">
        <el-input-number
          v-model="queryParams.pushCount"
          placeholder="请输入推送次数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="Position" @click="handlePushByQuery" v-loading="handlePushByQueryLoading">推送过滤数据</el-button>
        <h3>单次推送数据不要超过1000条</h3>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:localpic:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:localpic:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:localpic:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:localpic:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['manage:localpic:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Position"
          @click="handlePush"
          v-hasPermi="['manage:localpic:edit']"
        >推送选中数据</el-button>
      </el-col>
      
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Position"
          @click="handlePushByQuery"
          v-hasPermi="['manage:localpic:edit']"
        >推送过滤数据</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="localpicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="100" />
      <el-table-column label="图片链接" align="center" prop="pic" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.pic" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="图片类型" align="center" prop="picType">
        <template #default="scope">
          <dict-tag :options="manage_pic_type" :value="scope.row.picType"/>
        </template>
      </el-table-column>
      <el-table-column label="数据推送时间" align="center" prop="conTime" />
      <el-table-column label="推送次数" align="center" prop="pushCount" />
      <el-table-column label="结构化数据" align="center" prop="structuredData" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Position" @click="handlePush(scope.row)" v-hasPermi="['manage:localpic:edit']">推送</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:localpic:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:localpic:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改本地图片对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="localpicRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图片链接" prop="pic">
          <image-upload v-model="form.pic"/>
        </el-form-item>
        <el-form-item label="图片类型" prop="picType">
          <el-select v-model="form.picType" placeholder="请选择图片类型">
            <el-option
              v-for="dict in manage_pic_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据推送状态" prop="condition">
          <el-input v-model="form.condition" placeholder="请输入数据推送状态" />
        </el-form-item>
        <el-form-item label="推送次数" prop="pushCount">
          <el-input v-model="form.pushCount" placeholder="请输入推送次数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

   
    <!-- 数据导入对话框 -->
    <el-dialog title="导入数据" v-model="importOpen" width="400px" append-to-body draggable>
      <el-button style="margin-left: 10px;" size="big" type="success" @click="importTemplate">下载导入模板</el-button><br/>
      <el-text type="warning" size="large">注意！！</el-text> <br/>
      <el-text type="Primary" size="large">需要填写图片链接和图片类型两项，不能为空</el-text>
      <el-text type="Primary" size="large">图片类型如下：</el-text><br/>
      <el-text type="Primary" size="large">西藏喇嘛正样本</el-text><br/>
      <el-text type="Primary" size="large">西藏喇嘛负样本</el-text><br/>
      <el-text type="Primary" size="large">打架正样本</el-text><br/>
      <el-text type="Primary" size="large">打架负样本</el-text><br/>
      <el-text type="Primary" size="large">西外国人-东南亚人1798</el-text><br/>
      <el-text type="Primary" size="large">外国人-俄罗斯人2828</el-text><br/>
      <el-text type="Primary" size="large">外国人-非洲黑人1047</el-text><br/>
      <el-text type="Primary" size="large">外国人-拉丁美洲人1280</el-text><br/>
      <el-text type="Primary" size="large">外国人-欧美白人1708</el-text><br/>
      <el-text type="Primary" size="large">外国人-中东人1807</el-text><br/>
      <el-text type="Primary" size="large">西藏喇嘛正样本-覆盖池</el-text><br/>
      <el-text type="Primary" size="large">测试分类</el-text><br/>

      <el-upload
        class="upload-demo"
        ref="uploadRef"
        :action="uploadExcelUrl"
        :headers="headers"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        :limit="1"
        :auto-upload="false">
        
        <template #trigger>
          <el-button  type="primary" >上传文件</el-button>
        </template>
        <el-button style="margin-left: 10px;" size="big" type="success" @click="submitUpload">提交</el-button>
        <div slot="tip" class="el-upload__tip">上传文件仅支持xls/xlsx，且不超过5MB</div>
      </el-upload>
    </el-dialog>



  </div>
</template>

<script setup name="Localpic">
import { listLocalpic, getLocalpic, delLocalpic, addLocalpic, updateLocalpic, pushDataToKafka, pushDataToKafkaByQuery } from "@/api/manage/localpic";
import { getToken } from "@/utils/auth";
const { proxy } = getCurrentInstance();
const { manage_pic_type } = proxy.useDict('manage_pic_type');

const localpicList = ref([]);
const open = ref(false);
const loading = ref(true);
const handlePushByQueryLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const baseUrl = import.meta.env.VITE_APP_BASE_API;
// 上传地址
const uploadExcelUrl = ref(import.meta.env.VITE_APP_BASE_API + "/manage/localpic/upload"); // 上传的图片服务器地址
// token获取
const headers = ref({ Authorization: "Bearer " + getToken() });

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pic: null,
    picType: null,
    condition: null,
    pushCount: null,
    structuredData: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

const importOpen = ref(false);

// 获取导入文件模板
function importTemplate(){
  const a = document.createElement('a')
  a.href = "/importLocalimage.xlsx"
  a.download = "导入模板.xlsx"
  a.style.display = 'none'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 打开导入页面
function handleImport() {
  importOpen.value = true;
}
const uploadRef = ref({});
//提交文件
function submitUpload() {
  uploadRef.value.submit();
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    //提示信息
    proxy.$modal.msgSuccess(res.msg);
    //关闭对话框
    importOpen.value = false;
    //重新查询页面
    getList();
  } else {
    proxy.$modal.msgError(res.msg);
  }
  //清空文件列表
  uploadRef.value.clearFiles();
  //关闭loading页面
  proxy.$modal.closeLoading();
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("提交失败");
  //清空文件列表
  uploadRef.value.clearFiles();
  //关闭loading页面
  proxy.$modal.closeLoading();
}

// 上传文件校验
const props = defineProps({
  modelValue: [String, Object, Array],
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  }
});
// 上传前loading加载,格式校验
function handleBeforeUpload(file) {
  let isExcel = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = props.fileType.some(type => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } 
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传，请稍候...");
  //number.value++;
}



/** 查询本地图片列表 */
function getList() {
  loading.value = true;
  listLocalpic(queryParams.value).then(response => {
    localpicList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    pic: null,
    picType: null,
    condition: null,
    pushCount: null,
    structuredData: null
  };
  proxy.resetForm("localpicRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加本地图片";
}



/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getLocalpic(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改本地图片";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["localpicRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateLocalpic(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLocalpic(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除本地图片编号为"' + _ids + '"的数据项？').then(function() {
    return delLocalpic(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 推送按钮操作
function handlePush(row){
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认推送本地图片编号为"' + _ids + '"的数据项？').then(function() {
    return pushDataToKafka(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("推送成功");
  }).catch(function() {});
  // proxy.$modal.msgSuccess("推送成功");
}


// 按搜索条件推送
function handlePushByQuery(){
  handlePushByQueryLoading.value = true;
  pushDataToKafkaByQuery(queryParams.value).then(response => {
    handlePushByQueryLoading.value = false;
    proxy.$modal.msgSuccess("推送成功"+response.data+"条数据");
    getList();
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/localpic/export', {
    ...queryParams.value
  }, `localpic_${new Date().getTime()}.xlsx`)
}

getList();
</script>
